import axios from "axios";
import { ElLoading } from "element-plus";
import {
  requestInterceptor,
  responseInterceptor,
  requestErrorInterceptor,
} from "./interceptors";

/**
 * Workspace API 请求实例
 * 用于工作区相关接口
 */
const http = axios.create({
  baseURL: "http://lablims.glbpower.com:10001/workspace", // 线上
  withCredentials: true,
  timeout: 20000,
});

// Loading 实例
let loadingInstance;

/**
 * 显示 Loading
 */
const showLoading = () => {
  if (__GLOBAL_LOADING__) {
    loadingInstance = ElLoading.service({
      lock: true,
      text: "加载中请稍后...",
      background: "rgba(255, 255, 255, 0.5)",
      target: "body",
    });
  }
};

/**
 * 关闭 Loading
 */
const closeLoading = () => {
  if (__GLOBAL_LOADING__) {
    loadingInstance?.close();
  }
};

// 使用工厂函数创建请求拦截器
http.interceptors.request.use((config) => {
  // 显示 loading
  showLoading();

  // 使用统一的请求拦截器
  return requestInterceptor()(config);
}, requestErrorInterceptor(closeLoading));

// 使用工厂函数创建响应拦截器
const { success, error } = responseInterceptor({
  closeLoading,
});

http.interceptors.response.use(success, error);

export default http;
